package com.example.demo.utils;

import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

@Component
public class CustomDateFormatter implements Formatter<Date> {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static Date timestampToDate(Long timestamp) {
        if (timestamp == null) {
            return null;
        }
        return new Date(timestamp * 1000);
    }

    @SuppressWarnings("null")
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, locale);
        return format.parse(text);
    }

    @SuppressWarnings("null")
    @Override
    public String print(Date object, Locale locale) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, locale);
        return format.format(object);
    }

    public static Date isoToDate(String isoDateTime) {
        if (isoDateTime == null) {
            return null;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            return format.parse(isoDateTime);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid ISO 8601 date format: " + isoDateTime, e);
        }
    }
}
